/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NewProject.java
 *
 * Created on Feb 3, 2011, 1:22:40 PM
 */
package workSpace;

import java.awt.Dimension;
import java.awt.Point;
import java.io.File;
import java.util.logging.Level;

/**
 *
 * @author leng
 */
public class NewProject extends javax.swing.JFrame {

    /**
     * The coordinates of the top left corner to the parent window.
     */
    protected Point __parentWindowCoordinates = null;
    /**
     * The size of the parent window.
     */
    protected Dimension __parentWindowSize = null;
    /**
     * point to main window
     */
    protected userInterface.GUI __gui = null;

    /**
     * Creates new form NewProject
     */
    public NewProject(userInterface.GUI _gui, Point _parentWindowCoordinates, Dimension _parentWindowSize) {
        // get values of imported variables
        this.__gui = _gui;
        this.__parentWindowCoordinates = _parentWindowCoordinates;
        this.__parentWindowSize = _parentWindowSize;

        // components init by JAVA system
        initComponents();

        // set screen location of this dialong
        setFramePosition();

        // set extra attributes to components
        setComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel_primaryArea = new javax.swing.JPanel();
        jLabel_projectname = new javax.swing.JLabel();
        jTextField_projectname = new javax.swing.JTextField();
        jLabel_info = new javax.swing.JLabel();
        jButton_ok = new javax.swing.JButton();
        jPanel_topTextArea = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jPanel_bottom = new javax.swing.JPanel();
        jButton_cancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Create New Project");
        setAlwaysOnTop(true);
        setBackground(new java.awt.Color(238, 238, 239));
        setResizable(false);

        jPanel_primaryArea.setBackground(new java.awt.Color(240, 240, 240));

        jLabel_projectname.setFont(new java.awt.Font("Calibri", 1, 12)); // NOI18N
        jLabel_projectname.setText("New Project Name:");

        jLabel_info.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        jLabel_info.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/markerror.png"))); // NOI18N
        jLabel_info.setText("New Project Name:");

        jButton_ok.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
        jButton_ok.setText("OK");
        jButton_ok.setPreferredSize(new java.awt.Dimension(100, 24));
        jButton_ok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_okActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel_primaryAreaLayout = new org.jdesktop.layout.GroupLayout(jPanel_primaryArea);
        jPanel_primaryArea.setLayout(jPanel_primaryAreaLayout);
        jPanel_primaryAreaLayout.setHorizontalGroup(
            jPanel_primaryAreaLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel_primaryAreaLayout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel_primaryAreaLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel_primaryAreaLayout.createSequentialGroup()
                        .add(jLabel_projectname)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jTextField_projectname, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 403, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButton_ok, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(jPanel_primaryAreaLayout.createSequentialGroup()
                        .add(jLabel_info)
                        .addContainerGap(489, Short.MAX_VALUE))))
        );
        jPanel_primaryAreaLayout.setVerticalGroup(
            jPanel_primaryAreaLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel_primaryAreaLayout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel_primaryAreaLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel_projectname)
                    .add(jTextField_projectname, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jButton_ok, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 55, Short.MAX_VALUE)
                .add(jLabel_info)
                .addContainerGap())
        );

        getContentPane().add(jPanel_primaryArea, java.awt.BorderLayout.CENTER);

        jPanel_topTextArea.setBackground(new java.awt.Color(253, 253, 253));
        jPanel_topTextArea.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153)));

        jLabel1.setFont(new java.awt.Font("Cambria", 1, 14)); // NOI18N
        jLabel1.setText("Create a new project");

        jLabel2.setFont(new java.awt.Font("Cambria", 0, 14)); // NOI18N
        jLabel2.setText("<html>Please assign a name to this project. eHOST will create a directory under  <p>your current workspace using this name.</html>");

        org.jdesktop.layout.GroupLayout jPanel_topTextAreaLayout = new org.jdesktop.layout.GroupLayout(jPanel_topTextArea);
        jPanel_topTextArea.setLayout(jPanel_topTextAreaLayout);
        jPanel_topTextAreaLayout.setHorizontalGroup(
            jPanel_topTextAreaLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel_topTextAreaLayout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel_topTextAreaLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel1)
                    .add(jLabel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(172, Short.MAX_VALUE))
        );
        jPanel_topTextAreaLayout.setVerticalGroup(
            jPanel_topTextAreaLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel_topTextAreaLayout.createSequentialGroup()
                .add(9, 9, 9)
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel_topTextArea, java.awt.BorderLayout.PAGE_START);

        jPanel_bottom.setBackground(new java.awt.Color(240, 240, 240));

        jButton_cancel.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
        jButton_cancel.setText("Cancel");
        jButton_cancel.setPreferredSize(new java.awt.Dimension(100, 24));
        jButton_cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_cancelActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel_bottomLayout = new org.jdesktop.layout.GroupLayout(jPanel_bottom);
        jPanel_bottom.setLayout(jPanel_bottomLayout);
        jPanel_bottomLayout.setHorizontalGroup(
            jPanel_bottomLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel_bottomLayout.createSequentialGroup()
                .addContainerGap(517, Short.MAX_VALUE)
                .add(jButton_cancel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
        );
        jPanel_bottomLayout.setVerticalGroup(
            jPanel_bottomLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel_bottomLayout.createSequentialGroup()
                .add(jButton_cancel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel_bottom, java.awt.BorderLayout.PAGE_END);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Set screen location of this dialog. It will be put on the middle of the
     * right work space.
     */
    private void setFramePosition() {

        int width = 617, height = 250;
        this.setSize(new Dimension(width, height));
        this.setPreferredSize(new Dimension(width, height));

        //##1## dialog called from the NAV pane, set this dialog in the middle
        // of right area

        if ((__parentWindowSize == null) || (__parentWindowCoordinates == null)) {
            log.LoggingToFile.log(Level.SEVERE, "error 1102031516:: fail to import jcomponents.");
            return;
        }


        int x1 = __parentWindowCoordinates.x + (int) ((__parentWindowSize.width - width) / 2);
        int y1 = __parentWindowCoordinates.y + (int) ((__parentWindowSize.height - height) / 2);
        this.setLocation(x1, y1);

        return;

    }

    /**
     * set some components just after loading the dialog, and before display it
     * on screen;
     */
    private void setComponents() {
        // hide the infor label after loading the dialog
        this.jLabel_info.setVisible(false);
    }

    private void jButton_okActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_okActionPerformed
        // after user clicked OK button, we need to varify the directory name
        // and create it if necessary;
        if (preCheck()) {
            // close this dialog
            this.dispose();
        } else {
            return;
        }

        // create this project folder
        createNewProjectFolder(jTextField_projectname.getText().trim());

        // update project list on NAV pane
        __gui.display_refreshNAV_WorkSpace();
}//GEN-LAST:event_jButton_okActionPerformed

    /**
     * Create a project by the given folder name; User this folder name
     */
    private void createNewProjectFolder(String foldername) {
        try {

            //##1##  make sure that the folder name is not be empty
            if ((foldername == null) || (foldername.trim().length() < 1)) {
                log.LoggingToFile.log(Level.SEVERE, "error 1102041049:: folder name could not be empty!!!");
                return;
            }

            String workspace = env.Parameters.WorkSpace.WorkSpace_AbsolutelyPath;

            //##2##  create main folder of this new project
            String path = workspace + File.separator + foldername.trim() + File.separator;
            File newfolder = new File(path);
            if (!newfolder.mkdirs()) {
                log.LoggingToFile.log(Level.SEVERE, "error 1102041106:: fail to create folder for the new project!");
                return;
            }

            //##3## create subfolder of corpus for this project
            String corpuspath = path + "corpus" + File.separator;
            File corpus = new File(corpuspath);
            if (!corpus.mkdirs()) {
                log.LoggingToFile.log(Level.SEVERE, "error 1102041107:: fail to create 'corpus' folder under the new project!");
            }

            //##4## create subfolder of "saved" for this project
            String savedpath = path + "saved" + File.separator;
            File saved = new File(savedpath);
            if (!saved.mkdirs()) {
                log.LoggingToFile.log(Level.SEVERE, "error 1102041108:: fail to create 'saved' folder under the new project!");
            }


        } catch (Exception ex) {
            log.LoggingToFile.log(Level.SEVERE, "error 1102041050:: fail to create new project folder :["
                    + foldername
                    + "]\n"
                    + ex.toString());
        }
    }

    /**
     * Verify this new project name came from the text filed, and make sure
     * there is no any illegal char occurred.
     */
    private boolean preCheck() {
        String projectname = jTextField_projectname.getText();

        //##1## if projectname is null or empty
        if ((projectname == null) || (projectname.trim().length() < 1)) {
            this.jLabel_info.setText("Project name could not be empty!!!");
            this.jLabel_info.setVisible(true);
            commons.Tools.beep();
            return false;
        }


        //##2## check folder name for validity, symbols, such as '$' '&' could
        //      not appeared in the string
        char[] result = checkValidity(projectname);
        if (result != null) {
            String msg = "Wrong characters found:";
            for (char c : result) {
                if (c != ' ') {
                    msg = msg + " \'" + String.valueOf(c) + "\'";
                }
            }
            this.jLabel_info.setText(msg);
            this.jLabel_info.setVisible(true);
            commons.Tools.beep();
            return false;
        }


        //##3## if it exists and it's a file
        String msg = existAsFile(projectname.trim());
        if (msg != null) {
            this.jLabel_info.setText(msg);
            this.jLabel_info.setVisible(true);
            commons.Tools.beep();
            return false;
        }






        return true;

    }

    /**
     * Check whether a given name is existing as a FILE.
     *
     * @param foldername The simple name of the folder, no path.
     *
     * @return A string of error information if it's a file; or return null if
     * the given name isn't existing as a FILE.
     */
    private String existAsFile(String foldername) {
        try {
            if (foldername == null) {
                log.LoggingToFile.log(Level.SEVERE, "error 1102040942:: this filename is NULL.");
                return "folder name could not be empty.";
            }

            String workspacepath = env.Parameters.WorkSpace.WorkSpace_AbsolutelyPath;
            String path = workspacepath + File.separator + foldername.trim();

            File file = new File(foldername.trim());

            if (file.exists()) {
                if (file.isFile()) {
                    return "There already has a file named \""
                            + file.getName()
                            + "\" exists under your current workspace!!!";
                } else {
                    return "You already has a project called this name. ";
                }
            }


        } catch (Exception ex) {
            log.LoggingToFile.log(Level.SEVERE, "error 1102040001" + ex.getMessage());
        }

        return null;
    }

    /**
     * Check each character of the folder name to make sure characters of the
     * folder name are A-Z, a-z, 0-9, '-', '.', '~' or '_'; other special
     * characters will be replaced by ' '.
     *
     * @param foldername The name of the folder that we want to check all
     * characters of it to make sure the name of the new folder will be legal.
     *
     * @return  The filtered string that replaced all specific characters by ' '.
     */
    private char[] checkValidity(String foldername) {
        if ((foldername == null) || (foldername.trim().length() < 1)) {
            return null;
        }

        int size = foldername.length();
        char[] to_return = foldername.toCharArray();
        for (int i = 0; i < size; i++) {
            boolean flag = false;
            char thischar = foldername.charAt(i);
            if ((thischar <= 'Z') && (thischar >= 'A')) {
                flag = true;
            } else if ((thischar <= 'z') && (thischar >= 'a')) {
                flag = true;
            } else if ((thischar <= '9') && (thischar >= '0')) {
                flag = true;
            } else if (thischar == '-') {
                flag = true;
            } else if (thischar == '_') {
                flag = true;
            } else if (thischar == '.') {
                flag = true;
            } else if (thischar == '~') {
                flag = true;
            }

            if (flag) {
                to_return[i] = ' ';
            }
        }

        boolean flag = false;
        for (int i = 0; i < size; i++) {
            if (to_return[i] != ' ') {
                flag = true;
                break;
            }
        }

        if (flag) {
            return to_return;
        } else {
            return null;
        }
    }

    /**
     * Close this window after user clicked the button of "cancel"
     *
     * @param evt Mouse event.
     */
    private void jButton_cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_cancelActionPerformed
        this.dispose();
}//GEN-LAST:event_jButton_cancelActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton_cancel;
    private javax.swing.JButton jButton_ok;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel_info;
    private javax.swing.JLabel jLabel_projectname;
    private javax.swing.JPanel jPanel_bottom;
    private javax.swing.JPanel jPanel_primaryArea;
    private javax.swing.JPanel jPanel_topTextArea;
    private javax.swing.JTextField jTextField_projectname;
    // End of variables declaration//GEN-END:variables
}
